import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import VueCookies from 'vue-cookies'
import errorCode from '@/utils/errorCode'
import router from '../router'
/**
 * *********************************
 *  加入loading  防止无感操作
 * */
import { Loading } from 'element-ui';
let loadingInstance

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // 超时
  timeout: 10000
})
service.interceptors.request.use(config => {
  loadingInstance= Loading.service({ fullscreen: true ,background:"rgba(52,52,52,0.5)"})
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  const getToken=VueCookies.get('token')
  if (getToken && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})
service.interceptors.response.use(res => {

    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const message = errorCode[code] || res.data.msg || errorCode['default']
    if (code == 2003) {
      loadingInstance.close();
      MessageBox.confirm(
        '登录状态已过期，您可以继续留在该页面，或者重新登录',
        '系统提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        router.push({
                   path: '/Login',
                  })
          // 为了重新实例化vue-router对象 避免bug
      })
    } else if (code === 500) {
      Message({
        message: message,
        type: 'error'
      })
      loadingInstance.close();
      return Promise.reject(new Error(message))
    }  else if (code !== 200) {
      Notification.error({
        title: message
      })
      loadingInstance.close();
      return Promise.reject('error')
    } else {
      loadingInstance.close();
      return res.data
    }

  },
  error => {
    loadingInstance.close();
    console.log('err' + error)
    Message({
      message: '网络请求超时',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service
